package com.example.android.bigdialog;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class BigDialogActivity extends Activity {
    private final static String FRAGMENT_TAG_DIALOG = "dialog";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    public void clickSmallDialog(View v) {
        showMyDialog(MyDialogFragment.DIALOG_SIZE_SMALL);
    }

    public void clickBigDialog(View v) {
        showMyDialog(MyDialogFragment.DIALOG_SIZE_BIG);
    }
    
    private void showMyDialog(int sizeArg) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prefFragment = fm.findFragmentByTag(FRAGMENT_TAG_DIALOG);
        if (prefFragment != null) {
            ft.remove(prefFragment);
        }
        ft.addToBackStack(null);
        
        DialogFragment newDialogFragment = MyDialogFragment.newInstance(sizeArg);
        newDialogFragment.setCancelable(true);
        newDialogFragment.setShowsDialog(true);
//        newDialogFragment.setStyle(DialogFragment.STYLE_NORMAL,
//                android.R.style.Theme_Holo_DialogWhenLarge);
        newDialogFragment.show(ft, FRAGMENT_TAG_DIALOG);
    }
    
    public static class MyDialogFragment extends DialogFragment {

        private final static String ARG_TAG_SIZE = "size";
        public final static int DIALOG_SIZE_SMALL = 0;
        public final static int DIALOG_SIZE_BIG = 1;
        
        public MyDialogFragment() {
            // Fragment requires empty constructor
        }
        
        static MyDialogFragment newInstance(int sizeArg) {
            MyDialogFragment f = new MyDialogFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_TAG_SIZE, sizeArg);
            f.setArguments(args);
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            int size = this.getArguments().getInt(ARG_TAG_SIZE);
            getDialog().setTitle(size==1?R.string.btn_label_big:R.string.btn_label_small);
            View v = inflater.inflate(size==1?R.layout.frag_big:R.layout.frag_small, container, false);
            return v;
        }
        
        public void doClick(View v) {
            dismiss();
        }
    }
}
